//
//  NSObject+HDGoodsCollectManager.m
//  app
//
//  Created by D on 15/6/19.
//  Copyright (c) 2015年 hdaren. All rights reserved.
//

#import "HDGoodsCollectManager.h"
#import "HZRemoteResult.h"
#import "HZCategoryGoodsListData.h"
#import "SNFmdbManager.h"
#import "HDGoodCollectModel.h"

@interface HDGoodsCollectManager ()

@property (strong, nonatomic) JKHttpClient *http;
@property (strong, nonatomic) SNUniteUrl *uniteURL;
@property (strong, nonatomic) NSString * url;
@property (strong, nonatomic) SNFmdbManager * snFmdbManager;
@property (nonatomic,strong) NSMutableArray * mutableArray;
@property (nonatomic,strong) NSString * isRefresh;
@property (nonatomic,assign) BOOL isExist;

@end

@implementation HDGoodsCollectManager

+(HDGoodsCollectManager *)shareManager
{
    AS_SINGLETON(HDGoodsCollectManager, manager,{
        manager = [[HDGoodsCollectManager alloc]init];
        manager.http = [[JKHttpClient alloc]init];
        manager.mutableArray = [NSMutableArray array];
        manager.uniteURL = [SNUniteUrl shareUniteUrl];
        manager.snFmdbManager = [SNFmdbManager shareManager];
     
    })
    return manager;
    
}

//加载某分类下商品列表
- (void)loadOwnerGoodsListWithParams:(NSDictionary *)params result:(HDGoodsCollectResult *)result Refresh:(NSString *)refresh{
    
    self.isRefresh = refresh;
    
    [self.http showNetUnReachableToast];
    
    //发起请求之前先取消之前的请求
    [self.http cancel:self.uniteURL.per_favoriteGoodsUrl];
    
    //请求数据
    
    [self.http get:self.uniteURL.per_favoriteGoodsUrl params:params
            result:^(JKResponse *resp) {
                DLog(@"content = %d",resp.status);
                if (resp.OK) {
                    result.success = YES;
                    [self goodsListDataSourceWithArray:resp.content[@"list"]];
                }else if (resp.failure)
                {
                    result.failure = YES;
                }
                [result invoke];

            }];
}
//加载更多某分类下商品活动列表
- (void)loadMoreOwnerGoodsListWithParams:(NSDictionary *)params result:(HDGoodsCollectResult *)result Refresh:(NSString *)refresh{
    
    self.isRefresh = refresh;
    [self.http showNetUnReachableToast];
    
    //发起请求之前先取消之前的请求
    [self.http cancel:self.uniteURL.per_favoriteGoodsUrl];
    
    //请求数据
    [self.http get:self.uniteURL.per_favoriteGoodsUrl params:params
            result:^(JKResponse *resp) {
                
                if (resp.OK) {
                    
                    
                    }else{
                        
                    }
                    
                }
    ];
}

-(NSMutableArray*)goodsListDataSourceWithArray:(NSArray*)array
{
    NSDate * date = [NSDate date];
    [[NSUserDefaults standardUserDefaults] setObject:date forKey:@"goodsLastRefreshTime"];
    [self.mutableArray removeAllObjects];
    [self createFmdbToGoodsCollect];
    
    for (int i = 0 ; i < array.count; i++) {
        NSDictionary * dict = [array objectAtIndex:i];
        HDGoodCollectModel * model = [HDGoodCollectModel modelWithDict:dict];
        [self.mutableArray addObject:model];
        
        if (self.isRefresh.integerValue == 0) {
            [self saveDataToDB: model];
        }else
        {
            [self updataToDB:model];
        }
    }
    
    
    return self.mutableArray;
    
}
//创建商品收藏表
- (void)createFmdbToGoodsCollect
{
    NSString * sql = @"create table if not exists GoodsCollect(product_id TEXT PRIMARY KEY ,sale_num TEXT,sale_price TEXT ,shop_id TEXT, title TEXT,title_pic TEXT, dateline TEXT,lastid TEXT,delSign TEXT);";
    [self.snFmdbManager createTableWithSql:sql];
}
//保存到商品收藏表
-(void)saveDataToDB:(HDGoodCollectModel*)model
{
    [self.snFmdbManager.fmdbQueue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        
        NSString * sql = @"insert into GoodsCollect(product_id ,sale_num,sale_price, shop_id,title, title_pic,dateline,lastid,delSign) values (?, ?, ?, ?, ?, ?, ?, ?, ?);";
        NSArray * dataArr = @[model.product_id,model.sale_num,model.sale_price,model.shop_id,model.title,model.title_pic,model.dateline,model.lastid,model.delSign];
        
        if ([db executeUpdate:sql withArgumentsInArray:dataArr]) {
            DLog(@"成功保存到商品收藏表");
        }
        
        
    }];
}
//更新商品收藏表
-(void)updataToDB:(HDGoodCollectModel*)model
{
    [self.snFmdbManager.fmdbQueue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        
        NSString * sql = [NSString stringWithFormat:@"UPDATE GoodsCollect SET product_id = '%@', sale_num = '%@',sale_price = '%@',shop_id = '%@',title = '%@',title_pic = '%@',dateline = '%@',lastid = '%@', delSign = '%@' WHERE product_id = '%@' ",model.product_id,model.sale_num,model.sale_price,model.shop_id,model.title,model.title_pic,model.dateline,model.lastid,model.delSign,model.product_id];
        if ([db executeUpdate:sql]) {
            DLog(@"成功更新收藏列表");
        }
    }];
}



#pragma mark - 表是否存在
- (BOOL)fmdbIncludeFromGoodsList
{
    
    return [self.snFmdbManager fmdbIncludetableWithTableName:@"GoodsCollect"];
}

#pragma mark - 表中是否存有数据
- (BOOL)fmdbIncludeDataFromGoodsList
{
    
    return [self.snFmdbManager tabelIncludeDataWithTableName:@"GoodsCollect"];
}
#pragma mark - 是否自动刷新数据
- (BOOL)shouldRefreshGoodsListData
{
    NSFileManager * fm = [NSFileManager defaultManager];
    
    if ([fm fileExistsAtPath:kDBPath]) {//数据库文件已经存在
        //判断表是不是存在:
        if ([self fmdbIncludeFromGoodsList]) {//表是存在的
            //通过时间判断是否需要自动刷新
            NSUserDefaults * ud = [NSUserDefaults standardUserDefaults];
            NSDate * participationLastRefreshTime = [ud objectForKey:@"goodsLastRefreshTime"];
            NSDate * nowDate = [NSDate date];
            DLog(@"goodsLastRefreshTime ==== %@",participationLastRefreshTime);
            NSTimeInterval aTimer = [nowDate timeIntervalSinceDate:participationLastRefreshTime];
            DLog(@"goodsLast时间差  ===== %f",aTimer);
            if (aTimer > REFRESHSELFTIME) {//已经有一段时间没有刷新了,需要自动刷新
                DLog(@"goodsLast需要自动刷新");
                return YES;
            } else {//不需要自动刷新
                DLog(@"goodsLast不需要自动刷新");
                return NO;
            }
        } else {//表不存在,第一次进入此页面
            return YES;
        }
    } else {//数据库文件都不存在,第一次进入这个页面
        return YES;
    }
}

#pragma mark - 删除更新
-(void)updataAndDeleteToDB:(NSString*)product_id
{
    [self.snFmdbManager.fmdbQueue inTransaction:^(FMDatabase *db, BOOL *rollback) {
         NSString * sql = [NSString stringWithFormat:@"UPDATE GoodsCollect SET delSign = '%@' WHERE product_id = '%@' ",@"111",product_id];
        if ([db executeUpdate:sql]) {
            DLog(@"删除成功");
        }
    }];
}
#pragma mark - 从表中取出数据
- (NSMutableArray *)arrayFromFmdbGoodsList
{
    NSMutableArray * arr1 = [NSMutableArray array];
    NSMutableArray * arr2 = [NSMutableArray array];
    
    [self.snFmdbManager.fmdbQueue inTransaction:^(FMDatabase *db, BOOL *rollback) {
       
        FMResultSet * set_one = [db executeQuery:@"select * from sqlite_master where name  = 'GoodsCollect';"] ;
        if ([set_one next]){
            NSString * sql = @"select * from GoodsCollect;";
            FMResultSet * set = [db executeQuery:sql];
            [self.mutableArray removeAllObjects];
            while ([set next]) {
                
                NSString * product_id = [set stringForColumn:@"product_id"];
                NSString * sale_num = [set stringForColumn:@"sale_num"];
                NSString * sale_price = [set stringForColumn:@"sale_price"];
                NSString * shop_id = [set stringForColumn:@"shop_id"];
                NSString * title = [set stringForColumn:@"title"];
                NSString * title_pic = [set stringForColumn:@"title_pic"];
                NSString * dateline = [set stringForColumn:@"dateline"];
                NSString * lastid = [set stringForColumn:@"lastid"];
                NSString * delSign = [set stringForColumn:@"delSign"];
                
                NSDictionary * dict = @{@"product_id":product_id,
                                        @"sale_num":sale_num,
                                        @"sale_price":sale_price,
                                        @"shop_id":shop_id,
                                        @"title":title,
                                        @"title_pic":title_pic,
                                        @"dateline":dateline,
                                        @"lastid":lastid,
                                        @"delSign":delSign};
                
                [arr1 addObject:dict];
            }
            [set close];
        }
        [set_one close];

    }];
    [arr2 addObjectsFromArray:arr1];
    NSSortDescriptor*sorter=[[NSSortDescriptor alloc]initWithKey:@"dateline" ascending:NO];
    NSMutableArray *sortDescriptors=[[NSMutableArray alloc]initWithObjects:&sorter count:1];
    NSArray *sortArray=[arr2 sortedArrayUsingDescriptors:sortDescriptors];
    
    for (int i=0; i<[sortArray count]; i++) {
        if ([[[sortArray objectAtIndex:i] objectForKey:@"delSign"]integerValue] == 000) {
            [self.mutableArray addObject:[HDGoodCollectModel modelWithDict:[sortArray objectAtIndex:i]]];
        }
        
    }
    
    return self.mutableArray;
}

#pragma mark - 判断是否已收藏
-(BOOL)productIsExist:(NSString*)product
{
    NSMutableArray * arr1 = [NSMutableArray array];

    
    [self.snFmdbManager.fmdbQueue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        
        FMResultSet * set_one = [db executeQuery:@"select * from sqlite_master where name  = 'GoodsCollect';"] ;
        if ([set_one next]){
            NSString * sql = @"select * from GoodsCollect;";
            FMResultSet * set = [db executeQuery:sql];
            [self.mutableArray removeAllObjects];
            while ([set next]) {
                
                NSString * product_id = [set stringForColumn:@"product_id"];
                [arr1 addObject:product_id];
            }
            [set close];
        }
        [set_one close];
        
    }];
    
    for (int i = 0 ; i < arr1.count; i++) {
        if ([[arr1 objectAtIndex:i] isEqualToString:product]) {
            
            self.isExist = YES;
            return self.isExist;
        }else
        {
            self.isExist = NO;
        }
    }
    
    return self.isExist;
}

#pragma mark - 收藏插入
-(void)insertGoodsCollect:(NSArray*)array
{
    if ([[self arrayFromFmdbGoodsList]count] == 0) {
        [self createFmdbToGoodsCollect];
    }
    
    [self.snFmdbManager.fmdbQueue inTransaction:^(FMDatabase *db, BOOL *rollback) {
       
        NSString * sql = @"insert into GoodsCollect(product_id ,sale_num,sale_price, shop_id,title, title_pic,dateline,lastid,delSign) values (?, ?, ?, ?, ?, ?, ?, ?, ?);";
        if ([db executeUpdate:sql withArgumentsInArray:array]) {
            DLog(@"收藏成功");
        }
        
    }];
    
}

@end






